﻿/****************************** Module Header ******************************\
 * Module Name:  PageContext.cs
 * Module Version:  1.0.0 (2012-8-10)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used for PageContext.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

using System;
using System.Collections.Generic;
using System.Web;

namespace UCF.Core.Web
{
    public class PageContext
    {
        private static PageContext instance;
        public static PageContext Instance
        {
            get
            {
                if (instance == null || instance.Url.AbsoluteUri != HttpContext.Current.Request.Url.AbsoluteUri) instance = new PageContext();
                return instance;
            }
        }

        private Lazy<HttpContext> context = new Lazy<HttpContext>(() => HttpContext.Current);
        public HttpContext Context { get { return context.Value; } }

        private Lazy<HttpRequest> request = new Lazy<HttpRequest>(() => HttpContext.Current.Request);
        public HttpRequest Request { get { return request.Value; } }

        private Lazy<HttpResponse> response = new Lazy<HttpResponse>(() => HttpContext.Current.Response);
        public HttpResponse Response { get { return response.Value; } }

        private Lazy<HttpServerUtility> server = new Lazy<HttpServerUtility>(() => HttpContext.Current.Server);
        public HttpServerUtility Server { get { return server.Value; } }

        private Lazy<Uri> url = new Lazy<Uri>(() => HttpContext.Current.Request.Url);
        public Uri Url { get { return url.Value; } }

        public static void Write(string s, params object[] args)
        {
            if (string.IsNullOrEmpty(s)) return;
            HttpContext.Current.Response.Write(args.Length == 0 ? s : string.Format(s, args));
        }
        public static void WriteEnd(string s, params object[] args)
        {
            if (!string.IsNullOrEmpty(s)) HttpContext.Current.Response.Write(args.Length == 0 ? s : string.Format(s, args));
            HttpContext.Current.Response.End();
        }
        public static void Redirect(string s, params object[] args)
        {
            HttpContext.Current.Response.Redirect(string.Format(s, args));
        }
        #region Request对象扩展

        /// <summary>
        /// 获取Request请求的变量的字符串值
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="length">参数值长度，是防止sql攻击的一个辅助选项,0=不限</param>
        /// <returns></returns>
        public static string RequestString(string Key, int length)
        {
            HttpRequest request = HttpContext.Current.Request;
            string strOut = request.QueryString[Key];
            if (strOut == null) strOut = request.Form[Key];
            if (strOut == null) return "";
            if (length > 0 && strOut.Length > length) throw new Exception("参数长度超过限制");
            return strOut.Replace('\'', ' ');
        }

        /// <summary>
        /// 获取Request请求的变量的字符串值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static string RequestString(string Key)
        {
            return RequestString(Key, 0);
        }

        /// <summary>
        /// 获取Request请求的变量的整型值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static int RequestInteger(string Key, int defval = 0)
        {
            int iOut;
            return Int32.TryParse(RequestString(Key), out iOut) ? iOut : defval;
        }
        /// <summary>
        /// 获取Request请求的变量的short值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defval"></param>
        /// <returns></returns>
        public static short RequestShort(string key, short defval = 0)
        {
            short iOut;
            return short.TryParse(RequestString(key), out iOut) ? iOut : defval;
        }
        /// <summary>
        /// 获取Request请求的变量的Guid值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Guid RequestGuid(string key)
        {
            Guid g;
            return Guid.TryParse(RequestString(key), out g) ? g : Guid.Empty;
        }
        /// <summary>
        /// 获取Request请求的变量的时间类型的值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static DateTime RequestDateTime(string Key)
        {
            DateTime datOut;
            return DateTime.TryParse(RequestString(Key), out datOut) ? datOut : DateTime.Parse("1900-1-1");
        }

        /// <summary>
        /// 获取Request请求的变量的浮点类型的值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static double RequestDouble(string Key)
        {
            double dblOut;
            return Double.TryParse(RequestString(Key), out dblOut) ? dblOut : 0.00;
        }

        /// <summary>
        /// 获取Request请求的变量的浮点类型的值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static decimal RequestDecimal(string Key)
        {
            decimal dblOut;
            return decimal.TryParse(RequestString(Key), out dblOut) ? dblOut : 0.00m;
        }

        /// <summary>
        /// 获取Request请求的变量的布尔类型的值
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static bool RequestBool(string Key)
        {
            bool blnOut;
            return Boolean.TryParse(RequestString(Key), out blnOut) ? blnOut : false;
        }

        /// <summary>
        /// 获取指定名称的Cookie的字符串值
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        public static string RequestCookieString(string Name)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[Name];
            return cookie == null ? "" : cookie.Value;
        }

        /// <summary>
        /// 获取指定名称的Cookie的值的字典对象
        /// </summary>
        /// <param name="name"></param>
        /// <param name="splitGroup"></param>
        /// <param name="splitNameValue"></param>
        /// <returns></returns>
        public static Dictionary<string, string> RequestCookieDictionary(string name, string splitGroup, string splitNameValue)
        {
            string strValue = RequestCookieString(name);
            if (strValue.Length == 0) return new Dictionary<string, string>();
            return strValue.ToDictionary(splitGroup, splitNameValue);
        }
        /// <summary>
        /// 获取指定名称的Cookie的值的字典对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Dictionary<string, string> RequestCookieDictionary(string name)
        {
            return RequestCookieDictionary(name, "&", "=");
        }
        #endregion


        #region Response对象扩展

        /// <summary>
        /// 输出字符串
        /// </summary>
        /// <param name="text"></param>
        /// <param name="args"></param>
        public static void ResponseText(string text, params string[] args)
        {
            HttpContext.Current.Response.Write(string.Format(text, args));
        }
        /// <summary>
        /// 输出字符串，并可选择是否停止继续输出
        /// </summary>
        /// <param name="text"></param>
        /// <param name="endout"></param>
        /// <param name="args"></param>
        public static void ResponseText(string text, bool endout, params string[] args)
        {
            HttpContext.Current.Response.Write(string.Format(text, args));
            if (endout) HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 回显消息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="isJsWrite"></param>
        /// <param name="args"></param>
        public static void Echo(string text, bool isJsWrite, params object[] args)
        {
            text = isJsWrite ? string.Format(string.Format("document.write('{0}');", text), args) : string.Format(text, args);
            HttpContext.Current.Response.Write(text);
        }
        public static void EchoJ(string text, params object[] args)
        {
            Echo(text, true, args);
        }
        public static void EchoT(string text, params object[] args)
        {
            Echo(text, false, args);
        }

        /// <summary>
        /// 写入Cookie值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="args"></param>
        public static void ResponseCookie(string name, string value, params string[] args)
        {
            HttpContext.Current.Response.Cookies[name].Value = string.Format(value, args);
        }
        /// <summary>
        /// 写入Cookie值,并指定过期时间
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="expires"></param>
        /// <param name="args"></param>
        public static void ResponseCookie(string name, string value, DateTime expires, params string[] args)
        {
            HttpContext.Current.Response.Cookies[name].Value = string.Format(value, args);
            HttpContext.Current.Response.Cookies[name].Expires = expires;
        }

        /// <summary>
        /// 注销一个cookie对象
        /// </summary>
        /// <param name="name"></param>
        public static void ResponseCookieNull(string name)
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[name];
            if (cookie == null) return;
            cookie.Value = "";
            cookie.Expires = DateTime.Now.AddDays(-1); ;
        }

        #endregion

        /// <summary>
        /// 执行JavaScript脚本
        /// </summary>
        /// <param name="script"></param>
        public static void RunScript(string @script)
        {
            HttpContext.Current.Response.Write(string.Format(@"<script>{0}</script>", @script));
        }
    }
}
